import os

from typing import List, Dict, Any, Optional
import yaml

import settings
from utils.util_logger import logger


class YamlUtil:

    @classmethod
    def load_yaml(cls, file_path: str):
        full_yaml_path = os.path.join(settings.PROGRAM_PATH, "testcase") + file_path

        try:
            with open(full_yaml_path, "r", encoding="utf-8") as file:
                yaml_data_dict = yaml.safe_load(file)
            return yaml_data_dict  
        except FileNotFoundError as e:
            logger.error(f"{full_yaml_path} is not exists!")
        except Exception as e:
            logger.error(f"读取yaml异常： {e}")

    @classmethod
    def write_yaml(cls, file_path: str, data: Dict[str, Any]):
        """
            file_path: 具体测试用例的部分路径: /test_manager/extract_data.yaml
            data: 需要写入的键值对， 如： {"access_token": "sfsndsndksadas"}
        """
        full_yaml_path = os.path.join(settings.PROGRAM_PATH, "testcase") + file_path

        try:
            yaml_data_dict = cls.load_yaml(file_path)
        
            with open(full_yaml_path, "w", encoding="utf-8") as file:
                if yaml_data_dict:
                    for k, v in data.items():
                        yaml_data_dict[k] = v
                    yaml.safe_dump(yaml_data_dict, file)     
                else:  
                    yaml.safe_dump(data, file)
        except FileExistsError as e:
            print(f"{full_yaml_path} is not exists!")
        except Exception as e:
            print(f"写入yaml异常： {e}")
